<template>
  <div class="divBox relative">
    <el-card
      :bordered="false"
      shadow="never"
      class="ivu-mt"
      :body-style="{ padding: 0 }"
    >
      <div class="padding-add">
        <el-form :inline="true" @submit.native.prevent>
          <!-- <el-form-item label="用户搜索：" label-for="nickname">
            <UserSearchInput v-model="tableFrom" />
          </el-form-item> -->
          <el-form-item label="昵称搜索：">
            <el-input
              v-model.trim="playerName"
              @keyup.enter.native="getList(1)"
              placeholder="请输入用户昵称"
              class="selWidth"
              size="small"
              clearable
            />
          </el-form-item>
          <el-form-item label="报名时间：">
            <el-date-picker
              @change="onchangeTime"
              v-model="createTime"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              size="small"
              type="date"
              placement="bottom-end"
              placeholder="自定义时间"
              class="selWidth"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getList(1)">查询</el-button>
            <el-button size="small" @click="reset()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card mt14" :body-style="{ padding: '20px' }" :bordered="false" shadow="never">
      <div class="acea-row">
        <el-button
          type="primary"
          size="small"
          @click="handlerOpenEdit(0)"
          >新增用户</el-button
        >
      </div>
      <el-table v-loading="listLoading" :data="tableData.data" size="small" :highlight-current-row="true" class="mt20">
        <el-table-column label="ID" prop="euserId"  min-width="50" />
        <el-table-column label="头像" prop="avatar" min-width="80">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              class="avatar-image"
              :preview-src-list="[scope.row.avatar]"
            />
            <span v-else class="no-avatar">无头像</span>
          </template>
        </el-table-column>
        <el-table-column label="昵称" prop="playerName" min-width="100" :show-overflow-tooltip="true"> </el-table-column>
        <!-- <el-table-column label="国家" prop="country" min-width="100" :show-overflow-tooltip="true"> </el-table-column> -->
        <el-table-column label="报名时间" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <a @click="handlerOpenEdit(1, scope.row)">编辑</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="onAudit(scope.row, 'info')">参赛作品</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="handlerOpenDel(scope.row)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <!--详情-->
    <el-drawer
      custom-class="demo-drawer"
      direction="rtl"
      :visible.sync="dialogVisible"
      size="1000px"
      @close="onClose()"
    > 
       <el-table :data="balanceRecordData" size="small" class="mt20">
        <el-table-column label="作品ID" prop="id" min-width="80" />
        <el-table-column label="标题" prop="title" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column label="原创用户ID" prop="euserId" min-width="100" />
        <el-table-column label="作品类型" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === 1 ? 'primary' : 'success'">
              {{ scope.row.type === 1 ? '图文' : '视频' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="封面" min-width="100">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.cover" 
              :src="scope.row.cover" 
              class="cover-image" 
              :preview-src-list="[scope.row.cover]"
              fit="cover"
            />
            <span v-else class="no-cover">无封面</span>
          </template>
        </el-table-column>
        <el-table-column label="内容" prop="content" min-width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.content">{{ scope.row.content }}</span>
            <span v-else class="no-content">无内容</span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="创意分类" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="话题" min-width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="!scope.row.topicList || scope.row.topicList.length === 0">无话题</div>
            <div v-else>
              <el-tag
                v-for="(topic, index) in scope.row.topicList"
                :key="index"
                size="mini"
                class="topic-tag"
              >
                {{ topic }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推荐级别" min-width="100">
          <template slot-scope="scope">
            <el-rate disabled v-model="scope.row.star" v-if="scope.row.star !== null" />
            <span v-else class="no-star">无评分</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" min-width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.auditStatus === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 1" type="success">审核通过</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 2" type="danger">审核失败</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 3" type="info">平台关闭</el-tag>
            <span v-if="scope.row.refusal" class="refusal-reason">拒绝理由: {{ scope.row.refusal }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点赞数" prop="likeNum" min-width="80" />
        <el-table-column label="评论数" prop="replyNum" min-width="80" />
        <el-table-column label="分享数" prop="shareNum" min-width="80" />
        <el-table-column label="浏览量" prop="views" min-width="80" />
        <el-table-column label="设计过程" prop="designProcess" min-width="100" />
        <el-table-column label="参与设计人" prop="player" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="AI工具" prop="aitool" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column label="社区类型" prop="commType" min-width="100" />
        <el-table-column label="创建时间" prop="createTime" min-width="150" />
        <el-table-column label="更新时间" prop="updateTime" min-width="150" />
        <el-table-column label="操作时间" prop="operateTime" min-width="150" />
      </el-table>
    </el-drawer>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      :title="formTitle"
      :visible.sync="formDialogVisible"
      width="600px"
      :before-close="closeFormDialog"
    >
      <VirtualUserForm
        ref="virtualUserForm"
        :form-data="currentFormData"
        :is-edit="isEdit"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFormDialog">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit" :loading="false">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------
import * as community from '@/api/community';
import { checkPermi } from '@/utils/permission'; // 权限判断函数
import VirtualUserForm from './components/VirtualUserForm.vue'
export default {
  components: {
    VirtualUserForm
  },
  data() {
    return {
      tableFrom: {
        page: 1,
        limit: 20,
        playerName: '',
        createTime:'',
        applyTypes: '-1',
      },
      playerName: '',
      createTime: '',
      dialogVisible: false,
      balanceRecordData: [],
      paginationData: {
        total: 0,
      },
      tableData: {
        data: [],
        total: 0,
      },
      listLoading: false,
      keyNum: 0,
      id: 0,
      // 表单对话框相关
      formDialogVisible: false,
      formTitle: '新增用户',
      isEdit: false,
      currentFormData: {},
    };
  },
  mounted() {
    if (checkPermi(['platform:community:category:page:list'])) this.getList();
  },
  methods: {
    checkPermi,
    onchangeIsShow(row) {
      community.communityCategoryShowApi(row.id).then((res) => {
        this.$message.success('操作成功');
        this.getList();
      });
    },
    onClose() {
      this.dialogVisible = false;
    },
    // 选择时间
    selectChange(tab) {
      this.createTime = [];
      this.tableFrom.page = 1;
      this.getList();
    },
        // 具体日期
    onchangeTime(e) {
      console.log(e)
      this.tableFrom.createTime = e;
      this.tableFrom.page = 1;
      this.getList();
    },
    // 作品
    works(id) {
      this.listLoading = true;
      community
        .communityAddVirtualWorks(id)
        .then((res) => {
          console.log('参赛作品接口响应:', res)
          this.listLoading = false;
          // 响应拦截器已经返回了 res.data，所以直接使用 res.list 和 res.total
          this.balanceRecordData = res.list || [];
          this.paginationData.total = res.total || 0;
          console.log('处理后的作品数据:', this.balanceRecordData)
        })
        .catch((res) => {
          console.error('获取参赛作品失败:', res)
          this.listLoading = false;
          this.balanceRecordData = [];
          this.paginationData.total = 0;
        });
    },
    // 列表
    getList(num) {
      this.tableFrom.page = num ? num : this.tableFrom.page;
      this.tableFrom.playerName = encodeURIComponent(this.playerName);
      this.tableFrom.createTime = this.createTime;
      this.listLoading = true;
      community
        .communityAddVirtualListApi(this.tableFrom)
        .then((res) => {
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    reset() {
      this.tableFrom.playerName = '';
      this.tableFrom.applyTypes = '-1';
      this.playerName = '';
      this.selectChange();
      this.getList(1);
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList(1);
    },
    handlerOpenEdit(isCreate, editDate) {
      console.log(editDate)
      this.id = editDate ? editDate.euserId : 0;
      this.isEdit = isCreate === 1;
      this.formTitle = isCreate === 0 ? '新增用户' : '编辑用户';
      this.currentFormData = isCreate === 0 
        ? {
            playerName: '',
            country: '中国',
            avatar: ''
          }
        : Object.assign({}, editDate);
      this.formDialogVisible = true;
    },
    
    // 关闭表单对话框
    closeFormDialog() {
      this.formDialogVisible = false;
      this.currentFormData = {};
    },
    
    // 提交表单
    async handleFormSubmit() {
      try {
        const formRef = this.$refs.virtualUserForm;
        const formData = await formRef.validate();
        await this.submit(formData);
        this.closeFormDialog();
      } catch (error) {
        console.error('表单验证失败:', error);
      }
    },
    submit(formValue) {
      const data = {
        euserId: this.id,
        playerName: formValue.playerName,
        country: formValue.country || '中国',
        avatar: formValue.avatar || '',
      };
      
      return new Promise((resolve, reject) => {
        const apiCall = !this.id 
          ? community.communityAddVirtualAddApi(data)
          : community.communityAddVirtualUpdateApi(data);
          
        apiCall
          .then((res) => {
            this.$message.success('操作成功');
            this.getList();
            resolve(res);
          })
          .catch((error) => {
            this.$message.error('操作失败');
            reject(error);
          });
      });
    },
    handlerOpenDel(rowData) {
      this.$modalSure(
        '删除吗？',
      ).then(() => {
        community.communityAddVirtualDelApi(rowData.euserId).then((data) => {
          this.$message.success('删除成功');
          if (this.tableData.data.length === 1 && this.tableFrom.page > 1)
            this.tableFrom.page = this.tableFrom.page - 1;
          this.getList();
        });
      });
    },
        // 审核
    onAudit(row, type) {
      this.auditType = type;
      this.commentsInfo = row;
      this.id = row.id;
      this.dialogVisible = true;
      this.works(row.euserId)
    },
  },
};
</script>
<style scoped lang="scss">
.alert_title {
  margin-right: 10px;
}

.avatar-image {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  cursor: pointer;
}

.no-avatar {
  color: #999;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}

.cover-image {
  width: 60px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.no-cover {
  color: #999;
  font-size: 12px;
}

.topic-tag {
  margin-right: 4px;
  margin-bottom: 2px;
}

.refusal-reason {
  display: block;
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
}

.no-content {
  color: #999;
  font-size: 12px;
}

.no-star {
  color: #999;
  font-size: 12px;
}
</style>
